﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using JinianNet.JNCms.Models;

namespace JinianNet.JNCms.Controllers
{
    public class TemplateController : ControllerBase
    {
        public ActionResult List(int page = 1, int size = 0)
        {
             if (size <= 0)
                size = Config.Page.Size;
            return View(Data.DataAccess.CreateTemplate().GetList(page,size));
        }

        public ActionResult Service(int page = 1, int size = 0)
        {
            if (size <= 0)
                size = Config.Page.Size;
            List<Template> list = new List<Template>();
            try
            {
                Net.HttpUtils http = new Net.HttpUtils();
                http.Method = "POST";
                http.Url = Config.Read("Server", true)["TemplateServer"];
                http.Charset = Encoding.UTF8;
                string doc = http.Send(Encoding.UTF8.GetBytes(string.Concat("page=", page.ToString(), "&size=", size.ToString())));
                if (!string.IsNullOrEmpty(http.ErrorMessage))
                    throw new HttpException(http.ErrorMessage);
                XmlDocument xd = new XmlDocument();
                xd.LoadXml(doc);
                XmlNodeList xnl = xd.SelectSingleNode("Template").SelectNodes("List");

                foreach (XmlNode xn in xnl)
                {
                    Template model = new Template();
                    model.Author = xn.SelectSingleNode("Author").InnerXml;
                    model.CreateTime = DateTime.Parse(xn.SelectSingleNode("CreateTime").InnerXml);
                    model.Description = xn.SelectSingleNode("Description").InnerXml;
                    model.ID = int.Parse(xn.SelectSingleNode("ID").InnerXml);
                    model.Key = xn.SelectSingleNode("Key").InnerXml;
                    model.SystemVersion = xn.SelectSingleNode("SystemVersion").InnerXml;
                    model.Title = xn.SelectSingleNode("Title").InnerXml;
                    model.Url = xn.SelectSingleNode("Url").InnerXml;
                    model.Version = xn.SelectSingleNode("Version").InnerXml;
                    list.Add(model);
                }

                ViewBag.BaseUrl = xd.SelectSingleNode("Template").Attributes["Url"].Value;
                ViewBag.Error = null;
            }
            catch (HttpException e)
            {
                ViewBag.Error = e;
            }
            return View(list);
        }
    }
}
